<?php
namespace app\agent\controller\customer;

use app\agent\controller\Controller;
use app\agent\model\wxapp\Wxapp as WxappModel;
use app\agent\model\Shop as StoreShopModel;
use think\Db;
use think\Session;
use utils\Random;
use think\Config;
use app\admin\model\order\Order as OrderModel;
use app\store\model\Express as ExpressModel;
use app\store\model\store\shop\Clerk as ShopClerkModel;



class Customer extends Controller{
    /**
     * 商户首页
     */
    public function index(){
        $session = Session::get('yoshop_agent');
        $agent_id = $session['agent']['agent_id'];
        $model = new WxappModel;
        //var_dump($model->getList(0,$agent_id));die;
        return $this->fetch('index', [
            'list' => $list = $model->getList(0,$agent_id),
        ]);
    }

    /*
     * 添加商户
     */
    public function add(){
        if (!$this->request->isAjax()) {
            //获取分类数据11
            $treeInfo=Db::name('industry')->select();
            $tree=tree($treeInfo);
            $this->assign('tree',json_encode($tree));
            return $this->fetch('add');
        }
        $session = Session::get('yoshop_agent');
        $data = $this->postData('agent');
        Db::startTrans();
        try{
            if($data['password']!=$data['password_confirm']){
                return $this->renderError('两次输入的密码不一致，请确认密码');
            }
            //手机号码格式验证
            if(!preg_match("/^[1]([3-9])[0-9]{9}$/",$data['company_tel'])){
                return $this->renderError('法人联系电话格式有误请重新输入');
            }
            //添加 wxapp Setting StoreUser WxappHelp WxappPage WxappCategory表数据
            $wxappData['app_id']=0;//小程序AppID
            $wxappData['app_secret']=0;//小程序AppSecret
            $wxappData['mchid']=0;//微信商户号id
            $wxappData['apikey']=0;//微信支付密钥
            $wxappData['cert_pem']=0;//证书文件cert
            $wxappData['key_pem']=0;//证书文件key
            $wxappData['is_recycle']=0;//是否回收
            $wxappData['is_delete']=0;//是否删除
            $wxappData['create_time']=time();//创建时间
            $wxappData['update_time']=0;//更新时间
            $wxappData['active']=0;//账户激活（0，未激活，1.已激活）
            $wxappData['agent_id']=$session['agent']['agent_id'];//代理商id
            $wxappData['finish_time']=time()+8640000;//到期时间
            $wxappData['years']=1;//服务年限
            $wxappData['wxapp_name']=$data['store_name'];//商户名称
            $wxappData['category1']=$data['industry1'];//一级分类id
            //$wxappData['category2']=$data['industry2'];//二级分类id
            $wxappData['data_type']=$data['data_type'];//1:小程序  2：公众号
            $wxappData['service_type']=2;//1:龙达  2：微股客

            if($data['merchant']){
                $wxappData['merchant']=$data['merchant'];
            }else{
                $wxappData['merchant']=1;
            }

            $wxappData['id_img_face_id']=$data['id_img_face_id'];//法人身份证正面
            $wxappData['id_img_back_id']=$data['id_img_back_id'];//法人身份证背面
            $salt=Random::alnum();
            $wxappData['password_confirm']=md5(md5($data['password_confirm'].$salt.config('salt')));//确认密码
            $wxappData['faren_num']=$data['company_tel'];//法人电话
            $wxappData['salt']=$salt;//密码盐
            //\think\Log::info('密码盐:'.$salt);
            $wxappData['password']= md5(md5($data['password'].$salt.config('salt')));
            //\think\Log::info('加密后的密码:'.$wxappData['password']);
            $wxappData['user_name']=$data['user_name'];
            $wxappData['store_name']=$data['store_name'];//商户wxapp名称
            $wxappData['realname']=$data['realname'];//法人姓名
            $wxappData['real_name']=$data['realname'];//store_user表姓名

            $wxappData['id_num']=$data['id_num'];//法人身份证号码
            $wxappModel=new WxappModel();
            $wxappId=$wxappModel->add($wxappData);
            //var_dump($wxappId);
            //添加门店信息（store_shop表）
            $storeShop['shop_name']=$data['store_name'];//门店名称
            $storeShop['logo_image_id']=$data['head_img_id'];//门店logo图片id
            $storeShop['linkman']=$data['realname'];//联系人 默认为商家法人姓名
            $storeShop['phone']=$data['company_tel'];//联系电话
            $storeShop['shop_hours']=0;//营业时间
            $storeShop['image_id_gh']=$data['image_id_gh'];//公户照片
            $storeShop['image_id_mtz']=$data['image_id_mtz'];//门头照片
            $storeShop['image_id_yyzz']=$data['image_id_yyzz'];//营业执照
            $storeShop['image_id_dn']=$data['image_id_dn'];//店内照片
            $storeShop['province_id']=$data['province_id'];//所在省份id
            $storeShop['city_id']=$data['city_id'];//所在城市id
            $storeShop['region_id']=$data['region_id'];//所在辖区id
            $storeShop['address']=$data['address'];//详细地址
            $storeShop['longitude']=0;//门店坐标经度
            $storeShop['latitude']=0;//门店坐标纬度
            $storeShop['geohash']=0;//
            $storeShop['summary']='';//门店简介
            $storeShop['sort']=0;//门店排序(数字越小越靠前)
            $storeShop['is_check']=0;//是否支持自提核销(0否 1支持)
            $storeShop['status']=0;//门店状态(0禁用 1启用)
            $storeShop['is_delete']=0;//是否删除
            $storeShop['wxapp_id']=$wxappId;//小程序id
            $storeShop['create_time']=time();//创建时间
            $storeShop['update_time']=0;//更新时间
            $storeShopModel=new StoreShopModel();
            $res=$storeShopModel->add($storeShop);
            Db::commit();

            if($res){
                return $this->renderSuccess('添加成功',url('customer.customer/index'));
            }
            return $this->renderError('添加失败');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError('添加失败');
        }

    }

    /*
     * 获取当前代理所有添加的商户流水
     */
    public function water(){
        $session = Session::get('yoshop_agent');
        $agent_id = $session['agent']['agent_id'];
        $model = new WxappModel;
        $data=$this->request->param();
        $data['agent_id']=$agent_id;
        //var_dump($model->getwaterList($agent_id)->toArray());
        return $this->fetch('water', [
            'list' => $list = $model->getwaterList($data),
        ]);
    }

    /*
     * 商户收入
     */
    public function revenue(){
        $model = new WxappModel;
        $session = Session::get('yoshop_agent');
        $agent_id = $session['agent']['agent_id'];
        //$this->request->param()['agent_id']=$agent_id;
        $data=$this->request->param();
        $data['agent_id']=$agent_id;
        return $this->fetch('revenue', [
            // 充值记录列表
            'list' => $list = $model->getRevenueList($data),
        ]);
    }
    /*
     * 修改商户名称和密码
     */
    public function editMerchantInfo(){
        $salt=Random::alnum();
        $data['password']=input('post.password');
        if(empty($data['password'])){
            return ['code'=>-1,'msg'=>'新密码不能为空'];
        }
        $wxappData['password']= md5(md5($data['password'].$salt.config('salt')));
        if(!empty(input('post.username'))){
            $wxappData['user_name']=input('post.username');
        }
        $wxapp_id=input('post.wxapp_id');
        //判断用户名称是否重复
        $session = Session::get('yoshop_agent');
        $storeUserInfo=Db::name('store_user')->where(['wxapp_id'=>$wxapp_id,'is_super'=>1])->find();
        if(!$storeUserInfo){
            return ['code'=>-1,'msg'=>'要修改的信息不存在'];
        }
        $wxappData['salt']=$salt;
        $store=Db::name('store_user')->where(['wxapp_id'=>$wxapp_id,'is_super'=>1])->update($wxappData);
        if($store){
            return ['code'=>1,'msg'=>'修改成功'];
        }
        return ['code'=>0,'msg'=>'修改失败'];
    }

    public function detail($order_id){
        //订单详情
        $detail = OrderModel::detail($order_id);
        //物流公司列表
        $expressList = ExpressModel::getAll();
        //门店店员列表
        $shopClerkList = (new ShopClerkModel)->getList(true);
        return $this->fetch('detail', compact(
            'detail',
            'expressList',
            'shopClerkList'
        ));
    }
 
}